package com.burst.reptile.framework.security.handle;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import com.alibaba.fastjson.JSON;
import com.burst.reptile.common.constant.Constants;
import com.burst.reptile.common.utils.ServletUtils;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.framework.manager.AsyncManager;
import com.burst.reptile.framework.manager.factory.AsyncFactory;
import com.burst.reptile.framework.security.LoginUser;
import com.burst.reptile.framework.security.service.TokenService;
import com.burst.reptile.framework.web.result.Result;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

/**
 * 自定义退出处理类 返回成功
 * 
 * @author wujin
 * @date: 2020年5月21日 下午5:53:50
 */
@Configuration
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
	
	private final TokenService tokenService;

	/**
	 * 退出处理
	 * 
	 * @return
	 */
	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		LoginUser loginUser = tokenService.getLoginUser(request);
		if (ToolUtil.isNotEmpty(loginUser)) {
			String userName = loginUser.getUsername();
			// 删除用户缓存记录
			tokenService.delLoginUser(loginUser.getToken());
			// 记录用户退出日志
			AsyncManager.me().execute(AsyncFactory.recordLogininforLogout(userName, Constants.LOGOUT, "退出成功", request));
			// 删除cookie
	    	Cookie[] cookies = request.getCookies();
	    	if(ToolUtil.isNotEmpty(cookies)) {
	    		for (Cookie cookie : cookies) {
		             if (Constants.COOKIE_AUTH.equalsIgnoreCase(cookie.getName())) {
		                 Cookie temp = new Cookie(cookie.getName(), "");
		                 temp.setMaxAge(0);
		                 response.addCookie(temp);
		             }
		         }
	    	}
		}
		String header = request.getHeader("X-Requested-With");
		if(StrUtil.isNotEmpty(header) && StrUtil.equalsAnyIgnoreCase("XMLHttpRequest", header)) {
			ServletUtils.renderString(response, JSON.toJSONString(Result.success("退出成功")));
		}else {
			response.sendRedirect("/login"); 
		}
	}
}
